package com.guinea.core.acegi;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;

public class MyAuthenticationProcessingFilter extends
		AuthenticationProcessingFilter {
	private String defaultConsoleUrl;

	protected void successfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult)
			throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("Authentication success: " + authResult.toString());
		}

		SecurityContextHolder.getContext().setAuthentication(authResult);

		if (logger.isDebugEnabled()) {
			logger
					.debug("Updated SecurityContextHolder to contain the following Authentication: '"
							+ authResult + "'");
		}

		// Don't attempt to obtain the url from the saved request if
		// alwaysUsedefaultTargetUrl is set
		String targetUrl = false ? null : obtainFullRequestUrl(request);

		if (targetUrl == null) {
			boolean isConsoleUser = false;
			GrantedAuthority[] gas = authResult.getAuthorities();
			for (int i = 0; i < gas.length; i++) {
				GrantedAuthority g = gas[i];
				if(g == null) continue;
				if("role_console_user".equals(g.getAuthority()) || "admin".equals(g.getAuthority())){
					isConsoleUser = true;
					break;
				}
			}
			
			targetUrl = isConsoleUser ? getDefaultConsoleUrl() : getDefaultTargetUrl();
		}

		if (logger.isDebugEnabled()) {
			logger
					.debug("Redirecting to target URL from HTTP Session (or default): "
							+ targetUrl);
		}

		onSuccessfulAuthentication(request, response, authResult);

		getRememberMeServices().loginSuccess(request, response, authResult);

		// Fire event
		if (this.eventPublisher != null) {
			eventPublisher
					.publishEvent(new InteractiveAuthenticationSuccessEvent(
							authResult, this.getClass()));
		}

		sendRedirect(request, response, targetUrl);
	}

	public String getDefaultConsoleUrl() {
		return defaultConsoleUrl;
	}

	public void setDefaultConsoleUrl(String defaultConsoleUrl) {
		this.defaultConsoleUrl = defaultConsoleUrl;
	}

}
